package com.springboot.merlin.controller;

import com.springboot.merlin.config.PropertiesListenerConfig;
import com.springboot.merlin.properties.TestProperties;
import com.springboot.merlin.properties.UserProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author Merlin
 * @Title: PropertiesController
 * @ProjectName springboot-learning
 * @Description: TODO
 * @date 2018/8/2815:17
 */
@RestController
@RequestMapping("properties")
public class PropertiesController {

    /**
     *  Spring4.x 之后推荐构造函数的形式注入属性
     */
    private final UserProperties userProperties;

    private final TestProperties testProperties;

    @Value("${my.name}")
    private String name;

    @Autowired private Environment env;

    @Autowired
    public PropertiesController(UserProperties userProperties,TestProperties testProperties){
        this.userProperties = userProperties;
        this.testProperties = testProperties;
    }

    //方式一：通过@ConfigurationProperties方式
    @GetMapping("/1")
    public String properties1(){
        String properties = userProperties.toString();
        return properties;
    }


    @GetMapping("/2")
    public String properties2(){
        String properties = testProperties.toString();
        return properties;
    }

    //方式二：通过@Value 方式
    @GetMapping("/3")
    public String properties3(){
        return name;
    }

    //方式三：通过Environment方式
    @GetMapping("/4")
    public String properties4(){
        String name = env.getProperty("my.name");
        return name;
    }

    //方式四：PropertiesListener.java 用来初始化加载配置文件
    @GetMapping("/5")
    public String properties5(){
        Map<String, String> allProperty = PropertiesListenerConfig.getAllProperty();
        String str = allProperty.toString();
        return str;
    }


}
